package socket.socket01;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer {

    public static void main(String[] args) {
        SocketServer server = new SocketServer();
        server.connectServerSocket();

    }

    public void connectServerSocket() {
        try {
            //创建服务端Socket
            ServerSocket serverSocket = new ServerSocket(8088);
            //创建客户端
            Socket socket = null;
            while (true) {
                //监听客户端
                socket = serverSocket.accept();
                new ThreadSocket(socket).start();
                InetAddress address = socket.getInetAddress();
                System.out.println("当前客户端的IP：" + address.getHostAddress());
            }

        } catch (IOException ex) {

        }
    }

    class ThreadSocket extends Thread {

        private Socket socket = null;

        public ThreadSocket(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            InputStream inputStream = null;
            InputStreamReader inputStreamReader = null;
            BufferedReader br = null;
            OutputStream outputStream = null;
            PrintWriter pw = null;
            try {
                inputStream = socket.getInputStream();
                inputStreamReader = new InputStreamReader(inputStream);
                br = new BufferedReader(inputStreamReader);
                while (br.readLine() != null) {
                    System.out.println("客户端发送：" + br.readLine());
                }
                outputStream = socket.getOutputStream();
                pw = new PrintWriter(outputStream);
                pw.write("服务器欢迎你");
                pw.flush();
                socket.shutdownOutput();
            } catch (IOException ex) {
                ex.printStackTrace();
            } finally {
                try {
                    if (pw != null)
                        pw.close();
                    if (outputStream != null)
                        outputStream.close();
                    if (br != null)
                        br.close();
                    if (outputStream != null)
                        outputStream.close();
                    if (pw != null)
                        pw.close();
                    if (socket != null)
                        socket.close();
                } catch (IOException ex) {

                }
            }
        }
    }
}
